#include "pthread.hpp"
#include <vector>
#include <unistd.h>

void Print(std::string name)
{
    int cnt = 0;
    while (true)
    {
        std::cout << name << " is running, " << cnt++ << "." << std::endl;
        sleep(1);
    }
}

int tickets = 10000;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;

void GrabTicket(std::string name)
{
    while (true)
    {
        pthread_mutex_lock(&gmutex);
        if (tickets > 0)
        {
            usleep(1000);
            std::cout << name << " get ticket " << tickets-- << std::endl;
            pthread_mutex_unlock(&gmutex);
        }
        else
        {
            pthread_mutex_unlock(&gmutex);
            break;
        }
    }
}

int main()
{
    // 初始化
    std::vector<my::Thread> threads;
    for (int i = 0; i < 10; ++i)
    {
        std::string name = "Thread-" + std::to_string(1 + i);
        threads.emplace_back(name, GrabTicket);
    }

    // 启动
    for (auto &thread : threads)
    {
        thread.Start();
    }

    // sleep(10);
    // // 停止
    // for (auto &thread : threads)
    // {
    //     thread.Exit();
    // }

    // 主线程等待
    for (auto &thread : threads)
    {
        thread.Join();
    }
    return 0;
}